/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.runtime.datalist;

import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.contexts.WorkflowContext;
import cn.easyplatform.engine.runtime.RuntimeTask;
import cn.easyplatform.entities.BaseEntity;
import cn.easyplatform.entities.beans.list.ListBean;
import cn.easyplatform.entities.helper.EventLogic;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.response.PageResponseMessage;
import cn.easyplatform.messages.vos.PageVo;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.EntityType;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.util.MessageUtils;
import cn.easyplatform.util.RuntimeUtils;

import java.util.Map;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class DatalistTask implements RuntimeTask {

    @Override
    public IResponseMessage<?> doTask(CommandContext cc, BaseEntity bean) {
        WorkflowContext ctx = cc.getWorkflowContext();
        EventLogic el = RuntimeUtils.castTo(cc, ctx.getRecord(),
                ctx.getParameter("818"));
        if (el != null) {
            // 如果有上一个或者是从已有的触发的功能，在这里可以实行变量的声明以及mapping的处理
            // $xxx=@xxx
            // $表示当前的栏位或变量，@表示上一个功能的变量或栏位
            //
            ctx.getRecord().setParameter("808", Constants.ON_INIT);
            RecordContext[] rcs = ctx.getMappingRecord();
            String result = RuntimeUtils.eval(cc, el, rcs);
            if (!result.equals("0000"))
                return MessageUtils.byErrorCode(cc, ctx.getRecord(),
                        ctx.getId(), result);
        }
        ListBean lb = (ListBean) bean;
        ctx.setParameter("830", EntityType.DATALIST.getName());
        ctx.setParameter("831", lb.getId()).setParameter("832", lb.getName());
        ctx.setParameter("833", lb.getTable());
        return new PageResponseMessage(createPage(ctx, lb));
    }

    @Override
    public IResponseMessage<?> doNext(CommandContext cc,
                                      Map<String, Object> data) {
        return null;
    }

    private PageVo createPage(WorkflowContext ctx, ListBean lb) {
        PageVo pv = new PageVo();
        pv.setId(ctx.getId());
        String title = ctx.getParameterAsString("811");
        if (title != null) {
            if (title.charAt(0) == '$')
                title = (String) ctx.getRecord().getValue(title.substring(1));
        } else
            title = "";
        pv.setTitile(title);
        pv.setHeight(0);
        pv.setWidth(0);
        pv.setImage(ctx.getParameterAsString("813"));
        pv.setOpenModel(ctx.getParameterAsInt("805"));
        pv.setProcessCode(ctx.getParameterAsString("814"));
        pv.setVisible(ctx.getParameterAsBoolean("816"));
        StringBuilder sb = new StringBuilder();
        sb.append("<datalist id=\"").append(lb.getId()).append("\"");
        sb.append(" entity=\"").append(lb.getId()).append("\"");
        if (!Strings.isBlank(lb.getShowType()))
            sb.append(" type=\"").append(lb.getShowType()).append("\"");
        if (!Strings.isBlank(lb.getEditableColumns()))
            sb.append(" editableColumns=\"").append(lb.getEditableColumns())
                    .append("\"");
        if (!Strings.isBlank(lb.getPageId()))
            sb.append(" pageId=\"").append(lb.getPageId()).append("\"");
        if (!Strings.isBlank(lb.getGroupName()))
            sb.append(" group=\"").append(lb.getGroupName()).append("\"");
        if (!Strings.isBlank(lb.getLevelBy()))
            sb.append(" levelBy=\"").append(lb.getLevelBy()).append("\"");
        sb.append(" showPanel=\"").append(lb.isShowPanel()).append("\"");
        sb.append(" pageSize=\"").append(lb.getPageSize()).append("\"");
        sb.append(" showTitle=\"").append(lb.isShowTitle()).append("\"");
        sb.append(" showRowNumbers=\"").append(lb.isShowRowNumbers())
                .append("\"");
        sb.append(" sizedByContent=\"").append(lb.isSizedByContent())
                .append("\"");
        sb.append(" span=\"").append(lb.isSpan()).append("\"");
        sb.append(" checkmark=\"").append(lb.isCheckmark()).append("\"");
        sb.append(" multiple=\"").append(lb.isMultiple()).append("\"");
        if (ctx.getParameter("817") != null)
            sb.append(" event=\"next()\"");
        sb.append(" hflex=\"1\" vflex=\"1\"/>");
        pv.setPage(sb.toString());
        return pv;
    }

    @Override
    public IResponseMessage<?> doPrev(CommandContext cc) {
        WorkflowContext ctx = cc.getWorkflowContext();
        ListBean lb = cc.getEntity(ctx.getParameterAsString("831"));
        return new PageResponseMessage(createPage(ctx, lb));
    }
}
